/**
 *
 */

var app = angular.module('zhijiaoAdminApp.directives', []);


app.directive('menuPath', ['$rootScope', 'session', function ($rootScope, session) {
    return {
        restrict: 'A',
        link: function (scope, element, attr) {
            element.bind('click', function () {
                var exist = $rootScope.TabMenu.some(function (item) {
                    return item.access == attr.access;
                })
                if (!exist) {
                    $rootScope.TabMenu.push({name: element.text(), url: attr.menuPath, access: attr.access});
                }
                $rootScope.ActiveTabMenu = attr.access || '';
                $rootScope.menuStatus();
                console.log($rootScope.ActiveTabMenu)
                scope.location(attr.menuPath);
            })
        }
    };
}]);

app.directive('access', function ($rootScope) {
    return {
        restrict: 'A',
        link: function (scope, element, attr) {
            var access = window._access;
            if (!access[attr.access]) {
                element.remove();
            }
        }
    }
})


app.directive('adminPage', function ($compile) {
    return {
        restrict: 'A',
        scope: {
            adminPage: '=',   //总页数
            currPage: '=',    //当前页
            datasCount: '=',  //总条数
            callback: '=',     //回调
            noInit: '@',
        },
        link: function (scope, element, attr) {

            scope.page = function (page) {
                var pages = scope.adminPage;
                page < 1 && (page = 1);
                page > pages && (page = pages);
                page == 0 && (page = 1);
                scope.currPage = page;
                scope.goPage = scope.currPage;

                if (scope.callback) {
                    setTimeout(function () {
                        scope.callback();
                    }, 100)
                }
                element.html($compile(createTemplate())(scope));
            }
            scope.$watch('adminPage', function (val) {
                //if(scope.datasCount){
                element.html($compile(createTemplate())(scope));
                //}
            })

            var createTemplate = function () {
                var pages = scope.adminPage;
                var page = scope.currPage;

                var max_button = attr.pageButton || 10;
                var html = '';
                var count = attr.datasCount ? true : false;
                if (pages > 1) {
                    html = '<div class="btn-group">' +
                        '<button type="button" class="btn btn-white" ng-if="currPage > 1" ng-click="page(' + (scope.currPage - 1) + ')"><i class="fa fa-chevron-left"></i></button>';
                    var num = 0;
                    var start = page < 5 ? 1 : page - 5;
                    if (start < 1)
                        start = 1;

                    var end = start + max_button;
                    end > pages && (end = pages);
                    for (var i = start; i <= end; i++) {
                        if (num < max_button) {
                            html += '<button class="btn btn-white" ng-class="{active:' + (scope.currPage == i) + '}" ng-click="page(' + i + ')">' + i + '</button>';
                            num++;
                        }
                    }
                    html += '<button type="button" class="btn btn-white" ng-if="currPage < adminPage" ng-click="page(' + (scope.currPage + 1) + ')"><i class="fa fa-chevron-right"></i></button>';
                    html += '<input class="form-control" ng-model="goPage" style="width:40px;float:left;padding:0;text-align:center;"><button class="btn btn-white" ng-click="page(goPage)">跳转</button>';
                    html += '</div>';
                }
                if (count) {
                    html = '<span>总共{{datasCount}}条</span>' + html;
                }
                return html;
            }

            if (!scope.noInit) {
                scope.page(scope.currPage || 1);
            } else {
                createTemplate();
            }
            //scope.page(1);
        },
        replace: true,
    };
});

app.directive('datetimepicker', [function () {
    return {
        //require : '?ngModel',
        restrict: 'A',
        scope: {
            ngModel: '=',
        },
        link: function (scope, element, attr, ngModel) {
            var minDate = '2005/06/01';
            if (attr.nowDate) {
                var nowDate = new Date();
                var year = nowDate.getFullYear();
                var month = nowDate.getMonth() + 1;
                var day = nowDate.getDate();
                minDate = [year, month, day].map(item => {
                    return item < 10 ? '0' + item : item
                }).join('/');
            }

            scope.setVal = function () {
                if (attr.time) {
                    var str = element.val();
                    var date = str.substr(0, 10);
                    var time = str.substr(11, 5).split(':');
                    scope.$apply(function () {
                        scope.ngModel = date + ' ' + time.join(':');
                    })
                }
            }
            /*if(attr.time){
                attr.formate = 'Y-m-d H:i:s'
            }*/
            if (attr.time) {

                element.datetimepicker({
                    format: attr.formate || 'Y-m-d', //格式化时间
                    onSelectDate: function (dateText) {
                        scope.setVal();
                    },
                    onSelectTime: function () {
                        scope.setVal();
                    },
                    minDate: minDate
                });
            } else {
                element.datetimepicker({
                    format: attr.formate || 'Y-m-d', //格式化时间
                    timepicker: attr.formate == 'Y-m-d H:i' ? true : false,
                    onSelectDate: function (dateText) {
                        scope.setVal();
                    },
                    onSelectTime: function () {
                        scope.setVal();
                    },
                    minDate: minDate
                });
            }
            $.datetimepicker.setLocale('ch')
        }
    }
}])

app.directive('monthDatepicker', [function () {
    return {
        restrict: 'A',
        scope: {
            ngModel: '='
        },
        link: function (scope, element, attr) {
            element.datepicker({
                minViewMode: 1,
                autoclose: true,
                format: 'yyyy-mm'
            })
        }
    }
}])

app.directive('editor', [function () {
    return {
        restrice: 'A',
        scope: {
            ngModel: '='
        },
        link: function (scope, element, attr) {
            UE.delEditor(attr.id);
            var ue = UE.getEditor(attr.id, {
                zIndex: attr.zindex || 3000,
                autoHeightEnabled: false
            });
            ue.ready(function () {
                ue.setHeight(attr.height || 600);
                ue.setContent(scope.ngModel);
                ue.addListener('contentChange', function () {
                    setTimeout(function () {
                        var content = ue.getContent();
                        console.log(content)
                        scope.$apply(function () {
                            scope.ngModel = content;
                        })
                    }, 100)
                })
                ue.addListener('afterinsertimage', function () {
                    var content = ue.getContent();
                    scope.$apply(function () {
                        scope.ngModel = content;
                    })
                })
            })

        }
    }
}])

app.directive('tree', ['$compile', function ($compile) {
    return {
        restrict: 'A',
        scope: {
            origin: '=',
            tree: "=",
            callback: "=", //展开时调用的方法
            itemClick: "=", //点击时调用的方法
        },
        link: function (scope, element, attr) {
            var createHtml = function (data, parent) {
                html = '';
                html += '<ul style="list-style:none;padding-left:15px;"><li ng-repeat="item in tree" >';
                html += '<div style="height:25px;">'
                    + '<i style="font-size:14px;" ng-click="expanded(item)" class="fa" ng-class="{\'fa-plus-square-o\' : item.children && item.expanded==false , \'fa-minus-square-o\' : item.expanded == true}"></i> '
                    + '<span style="line-height: 25px;cursor: pointer;" ng-style="{\'color\' : item.active ? \'red\' : \'#333\'}" ng-click="item_click(item)">[{{item.type|departmentType}}] {{item.name}}</span></div>'
                    + '<div ng-if="item.children" ng-show="item.expanded" tree="item.children" origin="origin" callback="callback" item-click="itemClick"></div>';
                html += '</li></ul>';
                return html;
            };
            scope.$watch('tree', function (rel) {
                if (rel.length) {
                    var html = createHtml(rel);
                    element.html($compile(html)(scope));
                }
            })
            scope.expanded = function (item) {
                if (item.expanded !== undefined) {
                    item.expanded = !item.expanded;
                    if (scope.callback)
                        scope.callback(item)
                }

            }
            scope.item_click = function (item) {
                item.active = true;
                if (scope.origin) {
                    var unActive = function (data) {
                        data.forEach(function (a) {
                            if (a.id != item.id) {
                                a.active = false;
                            }
                            if (a.children) {
                                unActive(a.children);
                            }
                        })
                    }
                    unActive(scope.origin);
                }

                if (item.expanded == false) {
                    scope.expanded(item);
                }
                if (scope.itemClick) {
                    scope.itemClick(item)
                }
            }

        },
        replace: true,
    }
}])

app.directive('icheck', [function () {
    return {
        restrict: 'A',
        scope: {
            ngModel: '=',
            checkall: '@', //选择全部
            itemData: '=', //当前数据
            checkResult: '=', //选择结果
        },
        link: function (scope, element, attr) {
            element.iCheck({checkboxClass: "icheckbox_square-green", radioClass: "iradio_square-green",})
            scope.$watch('ngModel', function (val) {
                if (val) {
                    element.parent().addClass('checked');
                } else {
                    element.parent().removeClass('checked');
                }
            })
            element.on('ifClicked', function (event) {
                var ckecked = element.parent().hasClass('checked');
                scope.ngModel = !ckecked;//!scope.ngModel;
                console.log(scope.ngModel);
                result(element.val(), scope.ngModel);
                element.iCheck(scope.ngModel ? 'check' : 'uncheck');
                if (attr.checkall) {
                    var child = element.parents('tr').find('input');
                    child.iCheck(scope.ngModel ? 'check' : 'uncheck')
                    child.each(function (i, item) {
                        result($(item).val(), scope.ngModel);
                    })
                    if (scope.itemData.children) {
                        scope.itemData.children.forEach(function (item) {
                            item.checked = scope.ngModel;
                        })
                    }
                }
            })
            var exist = function (val) {
                return scope.checkResult.some(function (item) {
                    return item == val;
                })
            }
            var result = function (val, type) {
                if (scope.checkResult) {
                    if (type) {
                        if (!exist(val)) {
                            scope.checkResult.push(val);
                        }
                    } else {
                        for (var i in scope.checkResult) {
                            if (scope.checkResult[i] == val) {
                                scope.checkResult.splice(i, 1);
                            }
                        }
                    }
                }
            }
        }
    }
}])


app.directive('uploadImg', ['$compile', 'ajaxService', 'layerService', 'toastPCService', function ($compile, ajax, layer, toast) {
    return {
        restrict: 'EA',
        scope: {
            imgPath: '=', //如果为数组就是多图上传
            imgMax: '@',   //图片最多好多张
            succ: '=', //上传成功回调
            del: '=',  //删除回调
        },
        template: `<div>
						<div>
							<div class="uploadImg" style="float:left;display:flex;justify-content:center;flex-direction:column;width:{{width}}px;height:{{height}}px;background-color:#fff;text-align:center;cursor:pointer;">
								<img ng-if="imgPath && !isArray" style="width:100%;height:100%" ng-src="{{imgPath}}">
							</div>
							<div ng-if="imgPath && isArray" >
								<div style="float:left;margin-left:5px;width:{{width}}px;height:{{height}}px;" ng-repeat="img in imgPath track by $index" ng-click="delImg($index)">
									<img style="width:100%;height:100%;" ng-src="{{img}}">
								</div>
							</div>
						</div>
						<div style="clear: both;"></div>
						<div ng-if="fixedWH">图片尺寸：{{fixedWH}}</div>
					</div>
					`,
        link: function (scope, element, attr) {
            scope.isArray = scope.imgPath instanceof Array;
            scope.width = attr.width || 50;
            scope.height = attr.height || 50;
            scope.fixedWH = attr.fixedWh || '';
            var hasUrl = scope.imgPath.length ? true : false;
            var full = attr.full ? 1 : 0;  //上传返回绝对地址
            var mim = element.find(".uploadImg").MultifunctionImageManage({
                viewMode: 0, // 2
                aspectRatio: parseFloat(attr.imgRatio),
                fixedWH: attr.fixedWh || '',
                quality: 1,
                size: 1024*10,
                selectToUpload: attr.selectToUpload == "true" ? true : false,
                succeedFun: function (result) {
                    if (scope.imgPath instanceof Array) {
                        if (!scope.imgMax) scope.imgMax = 7;
                        if (scope.imgPath.length >= parseInt(scope.imgMax)) {
                            toast.show(2, '最多只能上传' + scope.imgMax + '张图片');
                            return;
                        }
                    }
                    var base64 = result.cropper_base64 || result.base64;
                    var clear_base64 = result.cropper_completion_base64 || result.original_completion_base64;
                    ajax('uploadBase64', {
                        code: base64,
                        suffix: result.suffix,
                        type: 'img',
                        full: full
                    }, function (rel) {
                        if (!rel.code) {
                            if (scope.imgPath instanceof Array) {
                                scope.imgPath.push(rel.data.path ? rel.data.path : rel.data);
                                console.log()
                                element.find('.uploadImg .mim_image_box').remove();
                            } else {
                                scope.imgPath = rel.data.path ? rel.data.path : rel.data;
                            }
                            if (scope.succ) {
                                scope.succ(rel.data);
                            }
                        }
                        console.log(scope)
                    }, function () {

                    });
                }
            }).data("MultifunctionImageManage");

            scope.delImg = function (index) {
                layer.confirm('删除图片', '', function () {
                    if (scope.del) {
                        scope.del(index);
                    }
                    scope.$apply(function () {
                        scope.imgPath.splice(index, 1);
                    })
                })
            }
        },
        replace: true
    };
}])

app.directive('tencentMapMake', ['$compile', 'ngDialog', '$timeout', function ($compile, ngDialog, timeout) {
    return {
        restrict: 'EA',
        scope: {
            ngModel: '='
        },
        template: '<a class="btn btn-success btn-xs" ng-click="showMap()">选择坐标</a>',
        replace: true,
        link: function (scope, element, attr) {
            scope.map = {};
            scope.temp = '';
            scope.showMap = function () {
                ngDialog.open({
                    template: '<div class="modal-header"><h4 class="modal-title">选择坐标</h4></div>' +
                        '<div class="modal-content">' +
                        '<div class="searchTenxun">\n' +
                        '                    <input type="text" name="searchAddress"\n' +
                        '                      placeholder="请搜索地址"\n' +
                        '                           id="searchAddress"/>\n' +
                        '                    <button type="button" class="btn btn-success " ng-click="search()">搜索</button>\n' +
                        '                </div>' +
                        '<div class="col-sm-5 input-group"><div class="input-group-btn">' +
                        '</div></div><div id="container" style="width:100%;height:500px;" ></div>' +
                        '</div>' +
                        '<div class="modal-footer"><button type="submit" class="btn btn-success" ng-click="confirm()" >确定</button>' +
                        '<button type="button" class="btn" ng-click="cancel()">取消</button></div>',
                    plain: true,
                    className: 'ngdialog-theme-default',
                    width: 900,
                    scope: scope,
                    closeByDocument: false,
                    closeByNavigation: true,
                })
                if(scope.ngModel.length!=2){
                    scope.ngModel = [29.570154,106.557045];
                }
                timeout(function () {
                    // 29.570154,106.557045
                    console.log(scope.ngModel)
                    var position = new qq.maps.LatLng(scope.ngModel[0], scope.ngModel[1]);
                    var map = new qq.maps.Map(document.getElementById("container"), {
                        center: position,
                        zoom: 13
                    });
                    var marker = marker = new qq.maps.Marker({
                        position: position,
                        draggable: true,
                        map: map
                    });
                    var info = new qq.maps.InfoWindow({
                        map: map
                    });
                    citylocation = new qq.maps.CityService({
                        complete: function (result) {
                            if (scope.ngModel) {
                                // var latLng = scope.ngModel.split(',');
                                result.detail.latLng.lat = scope.ngModel[0];
                                result.detail.latLng.lng = scope.ngModel[1];
                            }
                            marker.setMap(null);
                            //添加标记
                            map.setCenter(result.detail.latLng);
                            marker = new qq.maps.Marker({
                                position: result.detail.latLng,
                                draggable: true,
                                map: map
                            });
                            //添加到提示窗

                            qq.maps.event.addListener(map, 'click', function (e) {
                                marker.setMap(null);

                                marker = new qq.maps.Marker({
                                    position: e.latLng,
                                    draggable: true,
                                    map: map
                                });
                               /* info.open();
                                info.setContent('<div style="text-align:center;white-space:nowrap;' +
                                    'margin:10px;">坐标：' + e.latLng.lat + ',' + e.latLng.lng + '</div>');*/
                                info.setPosition(e.latLng);
                                scope.temp = [e.latLng.lat ,e.latLng.lng]
                            });
                        }
                    });
                    citylocation.searchLocalCity();

                    searchService = new qq.maps.SearchService({
                        complete: function (results) {
                            marker.setMap(null);
                            var pois = results.detail.pois;
                            if (pois) {
                                for (var i = 0, l = pois.length; i < 1; i++) {
                                    var poi = pois[i];
                                    map.setCenter(poi.latLng);
                                    //扩展边界范围，用来包含搜索到的Poi点
                                    scope.temp = [poi.latLng.getLat() , poi.latLng.getLng()]
                                    marker = new qq.maps.Marker({
                                        position: poi.latLng,
                                        draggable: true,
                                        map: map
                                    });
                                    info.open();
                                    info.setContent('<div style="text-align:center;white-space:nowrap;' +
                                        'margin:10px;">坐标：' + poi.latLng.getLat() + ',' + poi.latLng.getLng() + '</div>');
                                    info.setPosition(poi.latLng);
                                }

                            }
                        }
                    })

                }, 200)
            }
            scope.search = function () {
                searchService.search($('#searchAddress').val());
            }
            scope.confirm = function () {
                scope.ngModel = scope.temp;
                ngDialog.close();
            }
            scope.cancel = function () {
                ngDialog.close();
            }
        }
    };
}])

app.directive('noData', ['$compile', function ($compile) {
    return {
        restrict: 'A',
        scope: {
            noData: '=',
        },
        link: function (scope, element, attr) {
            var createHtml = function () {
                if (scope.noData.length == 0) {
                    var html = "<td colspan='" + element.parents('table').find('td').length + "'>暂无数据</td>";
                    element.html(html);
                } else {
                    element.html('');
                }
            }
            scope.$watch('noData', function (rel) {
                createHtml();
            })
        }
    };
}])

app.directive('selectLabel', ['ngDialog', 'ajaxService', 'tempDataService', 'toastPCService', function (ngDialog, ajax, tempData, toast) {
    return {
        restrict: 'EA',
        scope: {
            result: '='
        },
        link: function (scope, element, attr) {
            var iniChiled = function () {
                scope.result.forEach(item => {
                    scope.data.label.forEach(label => {
                        if (item.id == label.id) {
                            label.checked = true;
                        }
                    })
                })
            }
            var labelType = attr.labelType || 1;
            scope.data = {
                new_label: '',
                label: [],
                result: []
            };
            var label = tempData.get('label_list_' + labelType);
            if (label) {
                scope.data.label = label;
            } else {
                ajax('getLabelList', {type: labelType}, function (rel) {
                    scope.data.label = rel.data;
                    tempData.set('label_list_' + labelType, rel.data);
                })
            }
            element.on('click', function () {
                iniChiled();
                scope.data.new_label = '';
                ngDialog.open({
                    template: 'labelModal',
                    className: 'ngdialog-theme-default',
                    scope: scope,
                    width: 800,
                    closeByDocument: false,
                    closeByNavigation: true
                });
            })

            scope.addNewLabel = function () {
                var exist = scope.data.label.some(function (item) {
                    return item.name == scope.data.new_label
                });
                if (exist) {
                    return toast.show(2, '该标签已存在，请直接选择');
                }
                ajax('saveLabel', {label: scope.data.new_label, type: labelType}, function (rel) {
                    if (!rel.code) {
                        scope.data.label.push({id: rel.data, name: scope.data.new_label});
                        scope.data.new_label = '';
                    }
                })
            }

            scope.delLabel = function (index) {
                var item = scope.data.label[index];
                ajax('delLabel', {id: item.id, type: labelType}, function (rel) {
                    if (!rel.code) {
                        scope.data.label.splice(index, 1);
                        for (var i in scope.data.result) {
                            if (scope.data.result[i] == item.id) {
                                scope.data.result.splice(i, 1);
                            }
                        }
                    }
                })
            }

            scope.close = function () {
                scope.data.label.forEach(item => {
                    item.checked = false;
                })
                tempData.set('label_list_' + labelType, scope.data.label);
                ngDialog.close();
            }

            scope.commit = function () {
                var result = [];
                scope.data.result.forEach(id => {
                    scope.data.label.forEach(item => {
                        if (item.id == id) {
                            result.push({id: item.id, name: item.name});
                        }
                    })
                })
                scope.result = result;
                scope.close();
            }

            scope.cancel = function () {
                scope.close();
            }
        }
    }
}])

app.directive('keywordSearch', [function () {
    return {
        restrict: 'A',
        scope: {
            keywordSearch: '=', //选择的id
            ngModel: '=', //选择的名称
            searchUrl: '@',
            showField: '=',
            placeholder: '@',
        },
        template: `
			<div class="input-group">
				<input class="form-control" value="{{ngModel}}" placeholder="{{placeholder}}">
				<div class="input-group-btn">
					<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
						<span class="caret"></span>
					</button>
					<ul class="dropdown-menu dropdown-menu-right" role="menu"></ul>
				</div>
			</div>
		`,
        replace: true,
        link: function (scope, element, attr) {
            var params = {
                allowNoKeyword: false,   //是否允许无关键字时请求数据。为 false 则无输入时不执行过滤请求
                multiWord: true,         //以分隔符号分割的多关键字支持
                separator: ",",          //多关键字支持时的分隔符，默认为空格
                getDataMethod: "url",
                showHeader: false,
                //effectiveFields : ['name' , 'school_name'],
                //effectiveFieldsAlias : {name:'课程' , school_name : '机构'},
                idField: 'id',
                keyField: 'name',
                url: window._AppConfig.AjaxApi[scope.searchUrl].url,
                fnProcessData: function (rel) {
                    var index, len, data = {value: []};
                    data.value = rel.data;
                    return data;
                }
            };
            if (scope.showField) {
                params.showHeader = true;
                params.effectiveFields = [];
                for (i in scope.showField) {
                    params.effectiveFields.push(i);
                }
                params.effectiveFieldsAlias = scope.showField;
            }
            element.find('input').bsSuggest(params).on('onSetSelectValue', function (e, result) {
                scope.$apply(function () {
                    scope.keywordSearch = result.id;
                    scope.ngModel = result.key;
                })
                element.find('input').parent().find('table').hide();
            })
        }
    };
}])
app.directive('city', [function () {
    return {
        restrict: 'EA',
        scope: {
            result: '='
        },
        replace: true,
        template: `<div class="form-inline" style="margin-left:15px">
						<div class="form-group">
							<select class="form-control" ng-options="prov.id as prov.name for prov in province" ng-model="result[0]" ng-change="selectProvince()"></select>
						</div>
						<div class="form-group" ng-if="result[0]">
							<select class="form-control" ng-options="ci.id as ci.name for ci in city" ng-model="result[1]" ng-change="selectCity()"></select>
						</div>
						<div class="form-group" ng-if="result[1]">
							<select class="form-control" ng-options="ar.id as ar.name for ar in area" ng-model="result[2]" ng-change="selectArea()"></select>
						</div>
					</div>`,
        link: function (scope, element, attr) {
            var getCity = function (key) {
                var data = [];
                for (var i in ChineseDistricts[key]) {
                    var id = i;
                    if (id.length < 6) {
                        var len = 6 - id.length
                        for (var j = 0; j < len; j++) {
                            id += '0';
                        }
                    }
                    data.push({id: i, name: ChineseDistricts[key][i]});
                }
                return data;
            }
            scope.province = getCity(86);
            scope.province.unshift({id: '', name: '选择省份'});
            scope.city = [];
            scope.area = [];

            if (!scope.result) {
                scope.result = ['', '', ''];
            }

            scope.strToId = function (str, index) {
                var arrKey = ['province', 'city', 'area'];
                scope[arrKey[index]].forEach(val => {
                    if (val.name.indexOf(str.substr(0, 2)) !== -1) {
                        scope.result[index] = val.id;
                    }
                })
            }

            scope.$watch('result[0]', function (rel) {
                if (!/^\d+$/.test(rel)) {
                    return scope.strToId(rel, 0);
                }
                scope.city = getCity(scope.result[0]);
                scope.city.unshift({id: '', name: '选择城市'});
                if (scope.result[1]) {
                    if (!/^\d+$/.test(scope.result[1])) {
                        return scope.strToId(scope.result[1], 1);
                    }
                    var exist = scope.city.some(item => {
                        return item.id == scope.result[1]
                    });
                    if (!exist) scope.result[1] = '';
                }
            })
            scope.$watch('result[1]', function (rel) {
                scope.area = getCity(scope.result[1]);
                scope.area.unshift({id: '', name: '选择区县'});
                if (scope.result[2]) {
                    if (!/^\d+$/.test(scope.result[2])) {
                        return scope.strToId(scope.result[2], 2);
                    }
                    var exist = scope.area.some(item => {
                        return item.id == scope.result[2]
                    });
                    if (!exist) scope.result[2] = '';
                }
            })
        }
    };
}])

app.directive('clockpicker', [function () {
    return {
        restrict: 'A',
        scope: {
            ngModel: '='
        },
        link: function (scope, element, attr) {
            element.clockpicker({autoclose: true});
        }
    }
}])

app.directive('clickChangeInput', ['ajaxService', '$timeout', function (ajax, $timeout) {
    return {
        restrict: 'EA',
        scope: {
            value: '=',
            succ: '=',
            item: '='
        },
        replact: true,
        template: `<div style="width:100%">
						<span style="display:block;width:100%;cursor: pointer;" ng-click="showInput()" ng-if="!data.showInput">{{data.value}}</span>
						<input class="form-control" ng-if="data.showInput" ng-model="data.value">
					</div>`,
        link: function (scope, element, attr) {
            scope.data = {
                showInput: false,
                value: scope.value,
                initVal: scope.value
            }

            scope.showInput = function () {
                scope.data.showInput = true;
                $timeout(function () {
                    element.find('input').focus();
                    element.find('input').on('blur', function () {
                        console.log(11)
                        scope.$apply(function () {
                            scope.data.showInput = false;
                            if (scope.data.initVal != scope.data.value) {
                                scope.succ(scope.item, scope.data.value);
                            }
                        })
                    })
                }, 200)
            }

        }
    }
}])

//排序
app.directive('sortTab', ['$rootScope', function ($rootScope) {
    return {
        restrict: 'A',
        scope: {
            title: '@',
            key: '@',
            search: '=',
            call: '='
        },
        template: `<div style="cursor:pointer" ng-click="sort()">
			<span>{{data.text}}</span>
			<span ng-if="data.type">{{data.type == '1' ? '↓' : '↑'}}</span>
			<span ng-if="!data.type">↓↑</span>
		</div>`,
        link: function (scope, element, attr) {
            scope.data = {
                text: scope.title,
                type: 0,
            };
            // if(scope.search.order == undefined){
            scope.search.order = {};
            // }
            scope.sort = function () {
                if (scope.data.type == 0) {
                    scope.data.type = 1;
                } else {
                    scope.data.type = scope.data.type == 1 ? 2 : 1;
                }
                scope.search.order[scope.key] = scope.data.type;
                scope.call(1);
                scope.$emit('changeSort', {'key': scope.key});
            }
            $rootScope.$on('changeSort', function (event, data) {
                if (scope.key != data.key) {
                    scope.data.type = 0;
                }
            })
        },
    };
}])